import random
from typing import List
from paho.mqtt import client as mqtt_client
from json import loads, dumps
from dbs import crud
import time
from dbs.schemas import DatasBase
from dbs.database import SessionLocal
from datetime import datetime
topicList = ["smartHome_ByZX/00", "smartHome_ByZX/01", "/smartHome_ByZX/10", "smartHome_ByZX/11"]


class MQTTRecv:
    BROKER = '1.15.226.213'
    PORT = 1883
    TOPIC = "test"
    # generate client ID with pub prefix randomly
    CLIENT_ID = "python-mqtt-Server-IOT-FastAPI:{id}".format(id=random.randint(0, 1000))
    USERNAME = 'admin'
    PASSWORD = 'lgh656898'

    def __init__(self, topicList: List):
        self.client = self.connect_mqtt()
        for topic in topicList:
            self.client.subscribe(topic, qos=2)

    # def on_connect(client, userdata, flags, rc):
    #     if rc == 0:
    #         print("Connected to MQTT Broker!")
    #         client.subscribe(TOPIC)
    #     else:
    #         print("Failed to connect, return code {rc}".format(rc=rc), )

    def on_message(self, client, userdata, msg):
        db = SessionLocal()
        topic = msg.topic  # CGQ-data
        try:
            if topic in topicList:
                for data in loads(msg.payload.decode()):
                    if data["dataType"] == "cmd":
                        return

                    data["datetime"] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    crud.create_datas(db, DatasBase(**data))
        except Exception as e:
            pass

    def connect_mqtt(self):
        client = mqtt_client.Client(MQTTRecv.CLIENT_ID)
        client.username_pw_set(MQTTRecv.USERNAME, MQTTRecv.PASSWORD)
        # client.on_connect = self.on_connect
        client.on_message = self.on_message
        client.connect(MQTTRecv.BROKER, MQTTRecv.PORT)
        print("连接中")
        return client


if __name__ == '__main__':
    client = MQTTRecv(topicList)
    client.client.loop_forever()
